<template>
    <div class="user-info">
        <van-form @submit="onSubmit">
            <van-nav-bar
                    title="个人资料"
                    left-text="返回"
                    left-arrow
                    @click-left="onClickLeft"></van-nav-bar>
            <div class="item header">
                <div>头像：</div>
                <div>
                    <van-uploader
                            v-model="fileList"
                            preview-size="66"
                            :max-count="1"
                            :max-size="3 * 1024 * 1024"
                            :after-read="afterRead"
                    />
                </div>
            </div>
            <van-field
                    v-model="username"
                    name="username"
                    label="昵称"
                    placeholder="昵称不能为空.."
                    input-align="right"
                    error-message-align="right"
                    :clearable="true"
                    :colon="true"
                    :rules="[
                    { required: true, message: '昵称必须' },
                    { validator:checkUniqueUsername, message: '昵称已存在' },
                    { validator:checkUsernameLength, message: '昵称超过限制长度..' }
                    ]"
            />
            <van-field
                    label="邮箱"
                    name="email"
                    v-model="email"
                    input-align="right"
                    :colon="true"
                    disabled/>
            <div class="item">
                <div>年龄：</div>
                <div>
                    <van-stepper
                            v-model="age"
                            name="age"
                            theme="round"
                            button-size="22"
                            disable-input
                    />
                </div>
            </div>
            <van-divider class="divider"/>
            <div class="item">
                <div>性别：</div>
                <div>
                    <van-radio-group v-model="sex" name="sex" direction="horizontal">
                        <van-radio name="1">男</van-radio>
                        <van-radio name="2" checked-color="red">女</van-radio>
                    </van-radio-group>
                </div>
            </div>
            <van-divider class="divider"/>
            <van-field
                    v-model="motto"
                    name="motto"
                    rows="2"
                    autosize
                    label="个性签名"
                    type="textarea"
                    maxlength="50"
                    placeholder="请输入留言"
                    :colon="true"
                    :clearable="true"
                    :clickable="true"
                    show-word-limit
            />
            <div style="margin: 16px;">
                <van-button round block type="info" native-type="submit">
                    提交
                </van-button>
            </div>
        </van-form>
        <div class="tips">
            <div>* 我们重视您的个人信息，以上信息仅供本平台使用，不会泄漏您的隐私安全。</div>
        </div>
    </div>
</template>

<script>
    import Vue from 'vue';
    import {Field, Form} from 'vant';
    import {Area} from 'vant';
    import {Stepper} from 'vant';
    import {Button} from 'vant';
    import {Uploader} from 'vant';
    import {NavBar} from 'vant';
    import {Toast} from 'vant';
    import {Divider} from 'vant';
    import { RadioGroup, Radio } from 'vant';

    Vue.use(Radio);
    Vue.use(RadioGroup);
    Vue.use(Divider);
    Vue.use(Toast);
    Vue.use(NavBar);
    Vue.use(Uploader);
    Vue.use(Button);
    Vue.use(Stepper);
    Vue.use(Area);
    Vue.use(Form);
    Vue.use(Field);
    export default {
        name: "user-info",
        data() {
            return {
                username: "ATONG",
                email: "666666@qq.com",
                motto: "motto",
                age: 22,
                sex: "2",
                fileList: [],
            };
        },
        created() {
            var userInfo = JSON.parse(localStorage.getItem("userInfo")) || null;
            if (!userInfo) {
                Toast.fail("请先登陆！");
                this.$router.push('/my');
                return;
            }
            this.$store.commit("setPlayerStatus", false);
            this.$store.commit("setTabbarStatus", false);
            // 用户数据
            var defaultUsername = "未命名" + userInfo.id + "_" + Math.floor(Math.random() * 10000);
            this.username = userInfo.username || defaultUsername;
            this.motto = userInfo.motto;
            this.age=userInfo.age;
            this.sex = userInfo.sex || "1";
            this.fileList = [
                {
                    url: userInfo.avatar,
                    isImage: true
                },
            ]

        },
        methods: {
            // 返回
            onClickLeft() {
                this.$store.commit("setTabbarStatus", true);
                this.$router.push('/my');
            },
            // 上传图片
            afterRead(file) {
                var that = this;
                // 此时可以自行将文件上传至服务器
                let content = file.file;
                let data = new FormData();
                data.append('file', content);
                this.axios.post('/user/upload?from=avatar', data)
                    .then((response) => {
                        console.log(response);
                        var rs = response.data;
                        if (rs.code !== 1) {
                            // 失败提示
                            Toast.fail(rs.msg);
                        }
                        that.fileList[0].url = rs.data;
                        Toast.success("上传成功");
                    })
            },
            // 同步请求
            async checkUniqueUsername(username) {
                var response = await this.$http
                    .get("/user/checkUniqueUserName?username=" + username);
                return !response.data.data;
            },
            checkUsernameLength(username){
                return !(username.length > 15)
            },
            onSubmit(forms) {
                if(this.fileList.length <= 0){
                    Toast.fail("头像不能为空");
                    return false;
                }

                var params = {
                    username:this.username,
                    avatar:this.fileList[0].url,
                    age:this.age,
                    sex:this.sex,
                    motto:this.motto,
                };
                var that = this;
                var qs = require('qs');
                params = qs.stringify(params);
                this.$http.post("/user/edit",params).then((response)=>{
                    var rs = response.data;
                    if(rs.code == 1){
                        Toast.success("更新成功！");
                        setTimeout(function () {
                            // 更新缓存并跳转 /my
                            localStorage.setItem("userInfo", JSON.stringify(rs.data.user_info));
                            that.$router.push('/my');
                        }, 2000);
                    }else{
                        Toast.fail(rs.msg);
                    }
                })

            }
        },
    }
</script>

<style scoped>
    .user-info {

    }

    .item {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
        margin: 10px 15px 6px 15px;
        color: #333;
        font-size: 14px;
    }

    .divider {
        margin-left: 5%;
    }

    .header {
        margin-top: 20px;
    }

    .tips {
        margin: 20px;
        color: #7e8c8d;
        font-size: 10px;
    }
</style>